from src.utils import *
from src.db_tools import db_get_dreams, db_get_brief_dream
from src.error_handler import *
import pandas as pd

from app import create_app
app = create_app('development')

def dict_to_dataframe_dreams(dreams):
    for dream in dreams:
        # dream.pop("_id")
        # dream.pop("create_time")
        # dream.pop("last_update_time")
        tags = []
        for tag in dream["tags"]:
            tags.append(tag["value"])
        dream.pop("tags")
        dream["tags"] = tags
        dream["degree_code"] = dream["degree_info"]["degree_code"]
        dream.pop("degree_info")
        dream["dream_date"] = str(dream["dream_date"])[0:10]
    df = pd.DataFrame(dreams)
    df = df.sort_values(by = "dream_date")
    return df

def gen_barchart_data(headers):
    res = db_get_brief_dream(headers)
    if res.get("data", None) == None:
        return res
    try:
        df = dict_to_dataframe_dreams(res.get("data"))
        start_date = df.iloc[0,:]["dream_date"]
        end_date = df.iloc[-1,:]["dream_date"]
        stat_start_date = set_start_date(start_date)
        stat_end_date = set_end_date(end_date)
        ecart_date= define_ecart_date(stat_start_date, stat_end_date)
        app.logger.debug(ecart_date)

        option = {}
        xAxis = [{"type": 'category', "data": [], "axisTick" : { "alignWithLabel" : True }}]
        yAxis= [{"type": 'value',"axisTick": {"show": False}}]
        series = []
        degree_list = list(df["degree_code"].unique())
        for index_data,degree in enumerate(degree_list):
            serie = {}
            serie = { "name" : degree, "type" : "bar", "barWidth": "60%", "stack": "degree" }
            data = []
            for index,date in enumerate(ecart_date):
                if (index + 1) < len(ecart_date):
                    data.append(df[(df['dream_date'] < ecart_date[index + 1])&\
                                          (df['dream_date'] >= date)&(df["degree_code"] == degree)].shape[0])
                    if index_data is 0:
                        xAxis[0]["data"].append(date + " to " + ecart_date[index + 1])
            serie["data"] = data
            series.append(serie)
        option["legend"] = {"data" : degree_list}
        option["xAxis"] = xAxis
        option["yAxis"] = yAxis
        option["series"] = series
        option["total"] = df.shape[0]
        return {"code": 20000, "message": "Generate barchart option OK!", "data": option, "showMsg": False}
    except Exception as e:
        app.logger.error(str(e))
        return {"code": GEN_BARCHART_ERROR["code"], "message": GEN_BARCHART_ERROR["msg"], "showMsg": True, "typeMsg": "error"}

def get_tags_list(df):
    tags = {}
    for index, row in df.iterrows():
        for tag in row["tags"]:
            if tags.get(tag, None):
                tags[tag] = tags[tag] + 1
            else:
                tags[tag] = 1
    return tags

def gen_piechart_data(headers):
    res = db_get_brief_dream(headers)
    if res.get("data", None) == None:
        return res
    try:
        df = dict_to_dataframe_dreams(res.get("data"))
        option = {}
        option["name"] = "Tag"
        option["type"] = "pie"
        option["radius"] = [20, 170]
        option["roseType"] = "area"
        tags_count = []
        legend = {}
        tags_dict = get_tags_list(df)
        for (k,v) in tags_dict.items():
            ele = {"value": v, "name":k}
            tags_count.append(ele)
        option["data"] = tags_count
        legend["left"] = "center"
        legend["bottom"] = 10
        legend["data"] = list(tags_dict.keys())
        data = {"option" : option, "legend" : legend}
        return {"code": 20000, "message": "Generate piechart option OK!", "data": data, "showMsg": False}
    except Exception as e:
        app.logger.error(str(e))
        return {"code": GEN_PIECHART_ERROR["code"], "message": GEN_PIECHART_ERROR["msg"], "showMsg": True, "typeMsg": "error"}
